<?php

namespace app\admin\controller;

use app\admin\model\AdminLog;
use app\common\controller\Backend;
use think\Config;
use think\Hook;
use think\Session;
use think\Validate;
use think\Db;
/**
 * 后台首页
 * @internal
 */
class Index extends Backend
{

    protected $noNeedLogin = ['login'];
    protected $noNeedRight = ['index', 'logout'];
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();
        //移除HTML标签
        $this->request->filter('trim,strip_tags,htmlspecialchars');
    }

    /**
     * 后台首页
     */
    public function index()
    {
        
        // $kc = Db::name('shopro_goods')->where(['id'=>['between',['1663','1702']]])->select();
        // foreach($kc as $k=>$v){
        //     $sec = Db::name('shopro_goods')->where(['title'=>$v['title']])->where(['id'=>['lt',1663]])->order('id desc')->find();
        //     $sku = Db::name('shopro_goods_sku')->where(['goods_id'=>$sec['id']])->select();
        //     $r0 = 0;
        //     foreach($sku as $kk=>$vv){
        //         $rk = $vv;
        //         unset($rk['id']);
        //         $rk['goods_id'] = $v['id'];
        //         $rk['parent_id'] = $r0;
        //         if($vv['parent_id'] == 0){
        //             $ins = Db::name('shopro_goods_sku')->insertGetId($rk);
        //             $r0 = $ins;
        //         }else{
        //             $ins = Db::name('shopro_goods_sku')->insertGetId($rk);
                    
                    
        //             $skuprice = Db::name('shopro_goods_sku_price')->where(['goods_id'=>$sec['id'],'goods_sku_ids'=>$vv['id']])->find();
        //             $sp2 = $skuprice;
        //             unset($skuprice['id']);
        //             $skuprice['goods_sku_ids'] = $ins;
        //             $skuprice['goods_id'] = $v['id'];
        //             $skupp = Db::name('shopro_goods_sku_price')->insertGetId($skuprice);
        //             $skulog = Db::name('shopro_goods_stock_log')->where(['goods_id'=>$sec['id'],'goods_sku_price_id'=>$sp2['id']])->find();
        //              unset($skulog['id']);
        //             $skulog['goods_sku_price_id'] =$skupp;
        //             $skulog['goods_id'] = $v['id'];
        //             Db::name('shopro_goods_stock_log')->insert($skulog);
                    
        //         }
        //     }
            
            
        // }
        // p($kc);die;
        
        // $kc = Db::name('shopro_goods')->where(['category_ids'=>219])->select();
       
        // foreach($kc as $k=>$v){
        //     $res = $v;
        //     unset($res['id']);
        //     $res['category_ids'] = 255;
            
        //     $inid = Db::name('shopro_goods')->insertGetId($res);
            
        //     //sku
        //     $sku = Db::name('shopro_goods_sku')->where(['goods_id'=>$v['id'],'parent_id'=>0])->select();
        //     if($sku){
        //         //添加
        //         foreach($sku as $sk=>$sv){
        //             $skuk = $sv;
        //             unset($skuk['id']);
        //             $skuk['goods_id'] = $inid;
        //             $skuid = Db::name('shopro_goods_sku')->insertGetId($skuk);
        //             //第二层
        //             $skup = Db::name('shopro_goods_sku')->where(['goods_id'=>$v['id'],'parent_id'=>$sv['id']])->select();
                    
        //             if($skup){
        //                 foreach($skup as $sk1=>$sv1){
        //                     $skuk1 = $sv1;
        //                     unset($skuk1['id']);
        //                     $skuk1['goods_id'] = $inid;
        //                     $skuk1['parent_id'] = $sv1['id'];
                            
        //                     $skuid1 = Db::name('shopro_goods_sku')->insertGetId($skuk1);
                            
        //                     $skuprice = Db::name('shopro_goods_sku_price')->where(['goods_id'=>$v['id'],'goods_sku_ids'=>$sv1['id']])->find();
        //                     $sp2 = $skuprice;
        //                     unset($skuprice['id']);
        //                     $skuprice['goods_sku_ids'] = $skuid1;
        //                     $skuprice['goods_id'] = $inid;
        //                     $skupp = Db::name('shopro_goods_sku_price')->insertGetId($skuprice);
        //                     $skulog = Db::name('shopro_goods_stock_log')->where(['goods_id'=>$v['id'],'goods_sku_price_id'=>$sp2['id']])->find();
                            
        //                     unset($skulog['id']);
        //                     $skulog['goods_sku_price_id'] =$skupp;
        //                     $skulog['goods_id'] = $inid;
        //                     Db::name('shopro_goods_stock_log')->insert($skulog);
        //                 }
        //             }
        //         }
                
        //     }
        // }
        // p($kc);die;
        $cookieArr = ['adminskin' => "/^skin\-([a-z\-]+)\$/i", 'multiplenav' => "/^(0|1)\$/", 'multipletab' => "/^(0|1)\$/", 'show_submenu' => "/^(0|1)\$/"];
        foreach ($cookieArr as $key => $regex) {
            $cookieValue = $this->request->cookie($key);
            if (!is_null($cookieValue) && preg_match($regex, $cookieValue)) {
                config('fastadmin.' . $key, $cookieValue);
            }
        }
        //左侧菜单
        list($menulist, $navlist, $fixedmenu, $referermenu) = $this->auth->getSidebar([
            'dashboard' => 'hot',
            'addon'     => ['new', 'red', 'badge'],
            'auth/rule' => __('Menu'),
        ], $this->view->site['fixedpage']);
        $action = $this->request->request('action');
        if ($this->request->isPost()) {
            if ($action == 'refreshmenu') {
                $this->success('', null, ['menulist' => $menulist, 'navlist' => $navlist]);
            }
        }
        $this->assignconfig('cookie', ['prefix' => config('cookie.prefix')]);
        $this->view->assign('menulist', $menulist);
        $this->view->assign('navlist', $navlist);
        $this->view->assign('fixedmenu', $fixedmenu);
        $this->view->assign('referermenu', $referermenu);
        $this->view->assign('title', __('Home'));
        return $this->view->fetch();
    }

    /**
     * 管理员登录
     */
    public function login()
    {
        $url = $this->request->get('url', '', 'url_clean');
        $url = $url ?: 'index/index';
        if ($this->auth->isLogin()) {
            $this->success(__("You've logged in, do not login again"), $url);
        }
        //保持会话有效时长，单位:小时
        $keeyloginhours = 24;
        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password', '', null);
            $keeplogin = $this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:3,30',
                '__token__' => 'require|token',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                '__token__' => $token,
            ];
            if (Config::get('fastadmin.login_captcha')) {
                $rule['captcha'] = 'require|captcha';
                $data['captcha'] = $this->request->post('captcha');
            }
            $validate = new Validate($rule, [], ['username' => __('Username'), 'password' => __('Password'), 'captcha' => __('Captcha')]);
            $result = $validate->check($data);
            if (!$result) {
                $this->error($validate->getError(), $url, ['token' => $this->request->token()]);
            }
            AdminLog::setTitle(__('Login'));
            $result = $this->auth->login($username, $password, $keeplogin ? $keeyloginhours * 3600 : 0);
            if ($result === true) {
                Hook::listen("admin_login_after", $this->request);
                $this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $username, 'avatar' => $this->auth->avatar]);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ? $msg : __('Username or password is incorrect');
                $this->error($msg, $url, ['token' => $this->request->token()]);
            }
        }

        // 根据客户端的cookie,判断是否可以自动登录
        if ($this->auth->autologin()) {
            Session::delete("referer");
            $this->redirect($url);
        }
        $background = Config::get('fastadmin.login_background');
        $background = $background ? (stripos($background, 'http') === 0 ? $background : config('site.cdnurl') . $background) : '';
        $this->view->assign('keeyloginhours', $keeyloginhours);
        $this->view->assign('background', $background);
        $this->view->assign('title', __('Login'));
        Hook::listen("admin_login_init", $this->request);
        return $this->view->fetch();
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        if ($this->request->isPost()) {
            $this->auth->logout();
            Hook::listen("admin_logout_after", $this->request);
            $this->success(__('Logout successful'), 'index/login');
        }
        $html = "<form id='logout_submit' name='logout_submit' action='' method='post'>" . token() . "<input type='submit' value='ok' style='display:none;'></form>";
        $html .= "<script>document.forms['logout_submit'].submit();</script>";

        return $html;
    }

}
